package com.tianlan.blog.shiro;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianlan.blog.entity.SysResource;
import com.tianlan.blog.entity.SysRole;
import com.tianlan.blog.entity.SysUser;
import com.tianlan.blog.service.SysResourceService;
import com.tianlan.blog.service.SysUserRoleService;
import com.tianlan.blog.service.SysUserService;
import com.tianlan.common.base.component.JwtComponent;
import com.tianlan.common.exception.UnauthorizedException;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService userService;
    
    @Autowired
    private JwtComponent jwtComponent;
    
    @Autowired
    private SysUserRoleService sysUserRoleService;
    
    @Autowired
    private SysResourceService sysResourceService;

    
//    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//        //设置用于匹配密码的CredentialsMatcher
//        HashedCredentialsMatcher hashMatcher = new HashedCredentialsMatcher();
//        hashMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
//        hashMatcher.setStoredCredentialsHexEncoded(false);
//        hashMatcher.setHashIterations(1024);
//        super.setCredentialsMatcher(hashMatcher);
//    }
    
    @Override
    public boolean supports(AuthenticationToken token) {
        /**
         * 表示此Realm只支持JWTToken类型
         */
        return token instanceof JWTToken;
    }
    
    // 授权处理 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission,@RequiresRoles之类的
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    	JSONObject userObj = JSON.parseObject(principalCollection.toString());
        Integer userId = userObj.getInteger("id");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 查询角色
        ArrayList<String> roles = new ArrayList<>();
        // 查询权限
        ArrayList<String> permissions = new ArrayList<>();
        // 查询用户权限
        List<SysRole> roleList = sysUserRoleService.queryRolesByUserId(userId);
        for (SysRole role : roleList) {
            if (!StringUtils.isEmpty(role.getRoleKey())) {
                if (!StringUtils.isEmpty(role.getRoleKey().replace(" ", ""))) {
                    roles.add(role.getRoleKey());
                }
            }
            List<SysResource> resourceList = sysResourceService.queryResourceByRoleId(role.getId());
            if(!CollectionUtils.isEmpty(resourceList))
            {
                for (SysResource res : resourceList) {
                    if (!StringUtils.isEmpty(res.getResourceKey())) {
                        if (!StringUtils.isEmpty(res.getResourceKey().replace(" ", ""))) {
                            permissions.add(res.getResourceKey());
                        }
                    }
                }
            }
        }
        Set<String> rolesSet = new HashSet<>(roles);
        simpleAuthorizationInfo.addRoles(rolesSet);
        Set<String> permission = new HashSet<>(permissions);
        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }
 
    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。 认证处理
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws UnauthorizedException {
        String token = (String) auth.getCredentials();
        // 解密token获得username，用于和数据库进行对比
        String userAccount = jwtComponent.getUserAccount(token);
        if (userAccount == null) {
            throw new UnauthorizedException("token invalid");
        }
        SysUser userBean = userService.getUserByUserAccount(userAccount);
        if (userBean == null) {
            throw new UnauthorizedException("User didn't existed!");
        }
        if (!jwtComponent.verify(token, userAccount, userBean.getUserPassword() + userBean.getSalt())) {
            throw new UnauthorizedException("Username or password error");
        }
        String userString = JSONObject.toJSONString(userBean);
        return new SimpleAuthenticationInfo(userString, token, this.getName());
    }
 
}